package com.blog.service.impl;


import com.blog.common.constant.ResultCode;
import com.blog.common.exception.BlogException;

import cn.hutool.core.util.ObjectUtil;
import com.blog.common.constant.ResultCode;

import com.blog.common.result.Result;
import com.blog.entity.User;
import com.blog.mapper.UserMapper;
import com.blog.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import com.blog.util.PasswordUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.security.NoSuchAlgorithmException;

/**
 * 用户服务实现类
 * 实现用户登录、注册、登出等操作
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {


    @Autowired
    UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param user 用户信息，包含账号和密码
     * @return 登录结果
     */
    @Override
    public User login(User user) throws NoSuchAlgorithmException {

        User userByAccount = userMapper.selectByUserAccount(user.getAccount());

        if (ObjectUtils.isEmpty(userByAccount)){
            throw new BlogException(ResultCode.USER_NOT_EXIST);
        }

        String newPassword = PasswordUtil.hashPassword(user.getPassword(), userByAccount.getSalt());
        if (!userByAccount.getPassword().equals(newPassword)){
            throw new BlogException(ResultCode.USER_LOGIN_ERROR);
        }
        return user;
    }

    /**
     * 用户注册
     *
     * @param user 用户信息，包含账号、密码、邮箱等
     * @return 注册结果
     */
    @Override
    public Result register(User user) throws NoSuchAlgorithmException {
        //判断是否为空
        if (user.getAccount() == null || user.getAccount().isEmpty()) {
            log.info("用户对象为空");
            return Result.error(ResultCode.BAD_REQUEST);
        }
        //不为空
        //在数据库中比对
        String account = user.getAccount();
        User selectByUserAccount = userMapper.selectByUserAccount(account);
        if (!ObjectUtil.isNull(selectByUserAccount)) {
            log.info("用户名重复,重复用户名为：{}", account);
            return Result.error(ResultCode.USER_HAS_EXISTED);//用户名重复返回

        }
        //密码加密
        String password = user.getPassword();
        String salt = PasswordUtil.generateSalt();
        password = PasswordUtil.hashPassword(password, salt);
        user.setPassword(password);
        user.setSalt(salt);
        //为空数据库没有这个用户则存入
        userMapper.insertUser(user);
        return Result.success();


    }

    /**
     * 用户登出
     *
     * @return 登出结果
     */
    @Override
    public Result logout() {
        // 登出逻辑处理
        return null;
    }
}
